import {Component} from '@angular/core';
import {FormControl, FormGroup, NonNullableFormBuilder, ReactiveFormsModule, Validators} from '@angular/forms';
import {NzFormControlComponent, NzFormDirective, NzFormItemComponent} from "ng-zorro-antd/form";
import {NzInputDirective, NzInputGroupComponent} from "ng-zorro-antd/input";
import {NzColDirective, NzGridModule, NzRowDirective} from "ng-zorro-antd/grid";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {LoginService} from "./login.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {Router} from "@angular/router";

@Component({
  imports: [
    NzFormDirective,
    NzFormItemComponent,
    ReactiveFormsModule,
    NzFormControlComponent,
    NzInputGroupComponent,
    NzInputDirective,
    NzRowDirective,
    NzColDirective,
    NzButtonComponent,
    NzGridModule
  ],
  selector: 'nz-demo-form-normal-login',
  templateUrl: 'login.component.html',
  standalone: true,
  styleUrl: 'login.component.css'
})
export class LoginComponent {

  constructor(private fb: NonNullableFormBuilder,
              private loginService: LoginService,
              private messageService: NzMessageService,
              private router: Router) {}

  validateForm: FormGroup<{
    username: FormControl<string>;
    password: FormControl<string>;
    remember: FormControl<boolean>;
  }> = this.fb.group({
    username: ['', [Validators.required]],
    password: ['', [Validators.required]],
    remember: [true]
  });

  submitForm(): void {
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
    const req = this.validateForm.value
    this.loginService.userLogin(req.username!, req.password!)
      .subscribe(() => {
        this.messageService.success('登录成功')
        this.router.navigate(['/home/user'])
    })
  }

}

